package cn.itcast.web.servlet;

import cn.itcast.pojo.Book;
import cn.itcast.service.BookService;
import cn.itcast.service.imp.BookServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/book/*")
public class BookServlet extends BaseServlet {
    private BookService bookService=new BookServiceImpl();
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Book> books = bookService.findAll();
        writeJson(response,books);

    }
    public void delBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        bookService.delBook(Integer.parseInt(id));
    }
    public void addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String time = request.getParameter("time");
        String type = request.getParameter("type");

        Book book = new Book();
        book.setName(name);
        book.setAuthor(author);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date stime = sdf.parse(time);
            book.setTime(stime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        book.setType(Integer.parseInt(type));
        bookService.addBook(book);
    }
}
